package com.dawn.sinaoption.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import weibo4j.User;
import weibo4j.Weibo;
import weibo4j.WeiboException;

import com.dawn.sinaoption.common.SinaCommon;
import com.dawn.sinaoption.service.SinaService;
import com.dawn.trademanage.bean.TradeInfoBean;
import com.dawn.trademanage.service.TradeManageService;
import com.dawn.usermanage.bean.UserPreference;
import com.opensymphony.xwork2.ActionSupport;

@Controller("sinaOptionAction")
@Scope("prototype")
public class SinaOptionAction extends ActionSupport implements SessionAware, ServletRequestAware {

	private static final long serialVersionUID = -4809462863722754095L;
	private static Logger logger = Logger.getLogger(SinaOptionAction.class);

	private Map<String, Object> session;
	private HttpServletRequest request;
	private InputStream inputStream;

	@Autowired
	private TradeManageService tradeManageService;

	@Autowired
	private SinaService sinaService;

	public String followAction() throws UnsupportedEncodingException {
		long userId = ((UserPreference) session.get("user")).getUserId();
		long tradeId = Integer.parseInt(request.getParameter("tradeId"));
		String result = doFollow(userId, tradeId);
		this.inputStream = new ByteArrayInputStream(result.getBytes("UTF-8"));
		return SUCCESS;
	}

	private String doFollow(long userId, long tradeId) {
		if (tradeManageService.findIsFollowed(userId, tradeId)) {
			return SinaCommon.REPEAT_FOLLOW_ERROR;
		}
		TradeInfoBean tradeInfo = tradeManageService.findTradeById(tradeId);
		if (tradeInfo == null) {
			return SinaCommon.DATASOURCE_ERROR;
		}
		if (userId == tradeInfo.getTuUserinfo().getUserId())
			return SinaCommon.FOLLOW_SELF_ERROR;
		String sinaId = tradeInfo.getTuUserinfo().getSinaInfoBean().getSinaId();
		Weibo weibo = SinaCommon.getWeibo(session);
		try {
			User user = weibo.createFriendship(sinaId);
			if (null == user)
				return SinaCommon.WEIBO_ERROR;
		} catch (WeiboException e) {
			return SinaCommon.WEIBO_ERROR;
		}
		boolean result = false;
		try {
			result = sinaService.sinaFollow(userId, tradeInfo);
		} catch (Exception e) {
			logger.error(userId + "关注" + tradeInfo.getTuUserinfo().getUserId() + "失败！");
		}
		if (result)
			return String.valueOf(tradeInfo.getUnitPrice());
		else {
			try {
				weibo.destroyFriendship(sinaId);
			} catch (WeiboException e) {
				logger.error("取消关注失败！");
			}
			return SinaCommon.FOLLOW_ERROR;
		}
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}
}
